<?php
/**
 * Create by Phpstorm
 * User: Peco
 * Date: 2019/12/16
 * Time: 10:47
 * CommonController.php
 */

namespace App\Services;
include_once 'OssStsServer/aliyun-php-sdk-core/Config.php';

use App\Traits\Setting;
use Sts\Request\V20150401 as Sts;

class AliOssSts
{

    /**
     * oss对象存储参数获取及其sts判断
     * @return array|bool
     * @throws \ClientException
     * @throws \ServerException
     */
    public static function getSts(){

        //获取参数
        $config = Setting::getStaticSettingCache(OSS_KEY);
        if( !$config ) return false;

        //直接返回
        if( !$config['RoleArn'] ){
            return ['data'=>
                ['AccessKeySecret'=>$config['AccessKeySecret'],
                    'AccessKeyId'=>$config['AccessKeyID'],
                    'Endpoint'=>$config['Endpoint'],
                    'BucketName'=>$config['BucketName'],
                    'Domain'=>$config['Domain']]];
        }

        //否则调用sts
        $accessKeyID = $config['AccessKeyID'];
        $accessKeySecret = $config['AccessKeySecret'];
        $roleArn = $config['RoleArn'];
        $tokenExpire = $config['TokenExpireTime'] ?: 900;
        $policy = read_file(__DIR__.'/OssStsServer/policy/all_policy.txt');

        $iClientProfile = \DefaultProfile::getProfile("cn-shanghai", $accessKeyID, $accessKeySecret);
        $client = new \DefaultAcsClient($iClientProfile);

        $request = new Sts\AssumeRoleRequest();
        $request->setRoleSessionName("client_name");
        $request->setRoleArn($roleArn);
        $request->setPolicy($policy);
        $request->setDurationSeconds($tokenExpire);
        $response = (array)$client->getAcsResponse($request);

        //获取
        $data = (array)data_get($response, 'Credentials');

        //在返回值中添加本该在前端定义的常量
        data_set($data, 'Endpoint', $config['Endpoint']);
        data_set($data, 'BucketName', $config['BucketName']);

        //返回数据
        return ['data'=>$data];

  }
}
